package cn.bone.admin.system.loginfo.controller;

import cn.bone.admin.base.bean.CommonResult;
import cn.bone.admin.base.bean.ResultFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/9/18.
 */
@RestController
@CrossOrigin
@RequestMapping("/sys/img")
public class ImgUploadController {

    @RequestMapping("/upload")
    public CommonResult upload(HttpServletRequest request){


        String path = "c:/upload/";
        List<String> imgList = new ArrayList<>();
        if(request instanceof MultipartRequest){
            MultipartRequest req = (MultipartRequest)request;
            Iterator<String> fileNames = req.getFileNames();
            fileNames.forEachRemaining(name->{
                List<MultipartFile> files = req.getFiles(name);
                files.forEach(file->{
                    System.out.println("getContentType:"+file.getContentType());
                    System.out.println("getName:"+file.getName());
                    System.out.println("getOriginalFilename:"+file.getOriginalFilename());

                    String tempFile = UUID.randomUUID().toString().replace("-", "");
                    int index = file.getOriginalFilename().lastIndexOf(".");
                    String fileName = tempFile + file.getOriginalFilename().substring(index);
                    String fullName = path + fileName;
                    System.out.println(fileName);

                    try {
                        file.transferTo(new File(fullName));
                        String url = "http://127.0.0.1:10020/" + fileName;
                        System.out.println(url);
                        imgList.add(url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            });
        }else{
            System.out.println("不是文件请求");
        }
        return ResultFactory.ok(imgList);
    }
}
